package com.hengpeng.msls.service.borrowinfo.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.persist.QueryResult;
import com.hengpeng.common.persist.query.DynamicQuery;
import com.hengpeng.common.persist.query.Projections;
import com.hengpeng.common.persist.query.Restrictions;
import com.hengpeng.common.persist.query.constants.QueryConstants.JoinType;
import com.hengpeng.common.persist.query.constants.QueryConstants.QueryType;
import com.hengpeng.common.util.DateTimeUtil;
import com.hengpeng.itfinbase.persist.BorrowInfo;
import com.hengpeng.itfinbase.persist.RepaymentPlan;
import com.hengpeng.itfinbase.persist.BorrowInfo.BorrowStatus;
import com.hengpeng.itfinbase.persist.BorrowInfo.DurationType;
import com.hengpeng.itfinbase.persist.InvestInfo;
import com.hengpeng.msls.service.ServiceFactory;
import com.hengpeng.msls.service.borrowinfo.BorrowInfoService;
import com.hengpeng.msls.vo.borrow.BorrowInfoVo;

@Lazy
@Service
public class BorrowInfoServiceImpl implements BorrowInfoService
{
	@Autowired
	private ServiceFactory serviceFactory;

	@Override
	public ServiceResult<List<BorrowInfo>> queryList(BorrowStatus[] status, Long borrowUserId, Integer curPage, Integer pageSize)
	{
		DynamicQuery query = new DynamicQuery(BorrowInfo.class);
		if (status != null && status.length > 0)
		{
			query.inArray("status", status);
		}
		if (borrowUserId != null)
		{
			query.eq("borrowUserId", borrowUserId);
		}
		query.desc("case status when 'RAISE' then 5 " + "when 'END' then 4 " + "when 'LOANING' then 3 "
				+ "when 'REPAYMENTING' then 2 " + "when 'REPAYMENTED' then 1 else 0 end  ");
		query.desc("createTime");
		
		
		query.setPageIndex(curPage);
		query.setPageSize(pageSize);
		query.setIsSearchTotalCount(true);
		query.setQueryType(QueryType.JDBC);
		QueryResult<BorrowInfo> result = serviceFactory.getProtFactory().remoteQuery(query, BorrowInfo.class);

		Long count = result.getTotalCount();
		ServiceResult<List<BorrowInfo>> serviceResult = new ServiceResult<List<BorrowInfo>>();// 设置返回值
		serviceResult.setReturnValue(result.getResults());
		serviceResult.setReturnListSize(count.intValue());
		return serviceResult;
	}

	@Override
	public Long queryCount(BorrowStatus[] status)
	{
		DynamicQuery query = new DynamicQuery(BorrowInfo.class);
		if (status != null && status.length > 0)
		{
			query.inArray("status", status);
		}
		return serviceFactory.getProtFactory().count(BorrowInfo.class,query);
	}

	@Override
	public Long queryInvestCount(Long borrowId)
	{
		DynamicQuery query = new DynamicQuery(InvestInfo.class);
		query.eq("borrowInfoId", borrowId);
		return serviceFactory.getProtFactory().count(InvestInfo.class,query);
	}

	@Override
	public BorrowInfo getBorrowInfo(Long id, BorrowStatus status)
	{
		DynamicQuery query = new DynamicQuery(BorrowInfo.class);
		query.eq("id", id);
		if (status != null)
		{
			query.eq("status", status);
		}
		return serviceFactory.getProtFactory().getEntity(query, BorrowInfo.class);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public ServiceResult<List<BorrowInfoVo>> queryMyList(BorrowStatus status, Long borrowUserId,Integer curPage, Integer pageSize)
	{
		/**
		 * select a.borrowName,a.borrowMoney,a.borrowDuration,a.borrowRate,a.repaymentedTime,a.status,
		 * a.borrowMoney,a.raiseMoney, sum(case b.status when 'UNSETTLE' then b.repayMoney/100 else 0 end), --待还本息
		 * sum(case b.status when 'UNSETTLE' then 1 else 0 end), --未还期数 sum(case b.status when 'REPAYMENTED' then
		 * b.repayMoney/100 else 0 end) --还款总额 from borrowinfo a,repaymentplan b where a.id=b.borrowInfoId and
		 * a.status=? and a.borrowUserId=? group by
		 * a.borrowName,a.borrowMoney,a.borrowDuration,a.borrowRate,a.repaymentedTime,a.status,
		 * a.borrowMoney,a.raiseMoney;
		 */
		List<BorrowInfoVo> dataList = new ArrayList<BorrowInfoVo>();
		DynamicQuery query = new DynamicQuery(BorrowInfo.class, "a");
		query.createAlias(RepaymentPlan.class, JoinType.LEFTJOIN, "b");
		query.on(Restrictions.eqProperty("a.id", "b.borrowInfoId"));
		query.addProjection(Projections.property("a.borrowName"));// 0
		query.addProjection(Projections.property("a.borrowMoney"));// 1
		query.addProjection(Projections.property("a.borrowDuration"));// 2
		query.addProjection(Projections.property("a.borrowRate"));// 3
		query.addProjection(Projections.property("a.repaymentedTime"));// 4
		query.addProjection(Projections.property("a.status"));// 5
		query.addProjection(Projections.property("a.raiseMoney"));// 6
		query.addProjection(Projections.property("sum(case b.status when 'UNSETTLE' then b.repayMoney + b.repayAddMoney else 0 end)"));// 7待还本息
		query.addProjection(Projections.property("sum(case b.status when 'UNSETTLE' then 1 else 0 end)"));// 8未还期数
		query.addProjection(Projections.property("sum(case b.status when 'REPAYMENTED' then b.repayMoney + b.repayAddMoney else 0 end)"));// 9还款总额
		query.addProjection(Projections.property("a.durType"));// 10
		query.addProjection(Projections.property("a.id"));// 11
		if (status != null)
		{
			query.eq("a.status", status);
		}
		else
		{// 默认显示还款中标的
			query.eq("a.status", BorrowStatus.REPAYMENTING);
		}
		query.eq("a.borrowUserId", borrowUserId);
		query.addGourp("a.borrowName");
		query.addGourp("a.borrowDuration");
		query.addGourp("a.borrowRate");
		query.addGourp("a.repaymentedTime");
		query.addGourp("a.status");
		query.addGourp("a.borrowMoney");
		query.addGourp("a.raiseMoney");
		query.addGourp("a.durType");
		
		
		DynamicQuery queryout = new DynamicQuery(query, "ou");
		queryout.setPageIndex(curPage);
		queryout.setPageSize(pageSize);
		queryout.setIsSearchTotalCount(true);
		queryout.setQueryType(QueryType.JDBC);
		
		System.out.println(queryout.getSqlResult().getSql());
		QueryResult result = serviceFactory.getProtFactory().remoteQuery(queryout, null);
		Long count = result.getTotalCount();
		ServiceResult<List<BorrowInfoVo>> serviceResult = new ServiceResult<List<BorrowInfoVo>>();// 设置返回值
		
		if (result.getResults() != null && result.getResults().size() > 0)
		{
			for (int i = 0; i < result.getResults().size(); i++)
			{
				Object[] obj = (Object[]) result.getResults().get(i);
				BorrowInfoVo vo = new BorrowInfoVo();
				vo.setId(Long.parseLong(String.valueOf(obj[11])));
				vo.setBorrowName(String.valueOf(obj[0]));
				vo.setBorrowMoney(Long.parseLong(String.valueOf(obj[1])));
				vo.setBorrowDuration(Integer.parseInt(String.valueOf(obj[2])));
				vo.setBorrowRate(Double.parseDouble(String.valueOf(obj[3])));
				vo.setRepaymentedTime(DateTimeUtil.formatToDate(String.valueOf(obj[4]), DateTimeUtil.DATE_FORMAT_YMD));
				vo.setStatus(BorrowInfo.BorrowStatus.valueOf(String.valueOf(obj[5])));
				vo.setRaiseMoney(Long.parseLong(String.valueOf(obj[6])));
				vo.setUnRepayMoney(Long.parseLong(String.valueOf(obj[7])));// 待还本息
				vo.setUnRepayNum(Integer.parseInt(String.valueOf(obj[8])));// 未还期数
				vo.setTotalRepayMoney(Long.parseLong(String.valueOf(obj[9])));// 还款总额
				vo.setDurType(DurationType.valueOf(String.valueOf(obj[10])));
				dataList.add(vo);
			}
		}
		serviceResult.setReturnValue(dataList);
		serviceResult.setReturnListSize(count.intValue());
		return serviceResult;
	}
}
